package com.witmore.neutron.ai.web.apiv2.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.PageInfo;
import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.db.entity.AgentDeploymentDO;
import com.witmore.neutron.ai.db.entity.AgentSceneTypeDO;
import com.witmore.neutron.ai.db.mapper.AgentDeploymentMapper;
import com.witmore.neutron.ai.db.mapper.AgentSceneTypeMapper;
import com.witmore.neutron.ai.web.annotation.NoLoginRequired;
import com.witmore.neutron.ai.web.controller.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import jakarta.validation.Valid;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 智能体广场相关接口
 *
 * @author 豆子高
 * @date 2025-09-17
 */
@NoLoginRequired
@Slf4j
@RestController
@RequestMapping("/v2/agent/plaza")
public class AgentPlazaControllerV2 {

    @Autowired
    private AgentDeploymentMapper agentDeploymentMapper;

    @Autowired
    private AgentSceneTypeMapper agentSceneTypeMapper;

    /**
     * 获取智能体广场列表（支持分页和筛选）
     */
    @GetMapping("/list")
    public ResponsePageResult<AgentDeploymentResponse> getAgentPlaza(@Valid AgentPlazaQuery query) {
        try {
            // 构建查询条件
            LambdaQueryWrapper<AgentDeploymentDO> queryWrapper = new LambdaQueryWrapper<AgentDeploymentDO>()
                    // 只查询已部署的
                    .eq(AgentDeploymentDO::getDeployStatus, (byte) 1)
                    .eq(query.getAgentSceneTypeId() != null, AgentDeploymentDO::getAgentSceneTypeId, query.getAgentSceneTypeId())
                    .and(StringUtils.hasText(query.getKeyword()), wrapper -> wrapper
                            .like(AgentDeploymentDO::getAgentName, query.getKeyword())
                            .or()
                            .like(AgentDeploymentDO::getAgentDesc, query.getKeyword()))
                    .orderByDesc(AgentDeploymentDO::getTotalChatCount)
                    .orderByDesc(AgentDeploymentDO::getCreateTime);


            // 分页查询
            Page<AgentDeploymentDO> page = agentDeploymentMapper.selectPage(
                    new Page<>(query.getPage(), query.getSize()),
                    queryWrapper
            );

            if (page.getRecords().isEmpty()) {
                return ResponsePageResult.success(new ArrayList<>(),
                        new PageInfo(query.getPage(), query.getSize(), 0L, 0L));
            }

            // 转换为VO
            List<AgentDeploymentResponse> deploymentVOs = new ArrayList<>();
            for (AgentDeploymentDO deployment : page.getRecords()) {
                AgentDeploymentResponse vo = AgentDeploymentResponse.fromEntity(deployment);
                deploymentVOs.add(vo);
            }

            // 构建返回结果
            PageInfo pageInfo = new PageInfo(query.getPage(), query.getSize(),
                    page.getTotal(), page.getPages());

            return ResponsePageResult.success(deploymentVOs, pageInfo);
        } catch (Exception e) {
            log.error("获取智能体广场列表失败", e);
            return ResponsePageResult.fail(500, e.getMessage());
        }
    }

    /**
     * 获取场景类型列表及统计信息
     */
    @GetMapping("/scene-types")
    public ResponseResult<List<AgentSceneTypeWithStatsResponse>> getAgentSceneTypesWithStats() {
        try {
            // 查询所有启用的场景类型
            List<AgentSceneTypeDO> sceneTypes = agentSceneTypeMapper.selectList(
                    new LambdaQueryWrapper<AgentSceneTypeDO>()
                            .eq(AgentSceneTypeDO::getStatus, (byte) 1)
                            .orderByAsc(AgentSceneTypeDO::getId)
            );

            // 统计每个场景类型下的智能体数量
            Map<Byte, Long> sceneTypeCountMap = agentDeploymentMapper.selectList(
                            new LambdaQueryWrapper<AgentDeploymentDO>()
                                    .eq(AgentDeploymentDO::getDeployStatus, (byte) 1)
                                    .isNotNull(AgentDeploymentDO::getAgentSceneTypeId)
                    ).stream()
                    .collect(Collectors.groupingBy(AgentDeploymentDO::getAgentSceneTypeId, Collectors.counting()));

            // 转换为响应对象并设置统计数量
            List<AgentSceneTypeWithStatsResponse> response = sceneTypes.stream()
                    .map(sceneType -> {
                        AgentSceneTypeWithStatsResponse item = AgentSceneTypeWithStatsResponse.fromEntity(sceneType);
                        // 设置该分类下的智能体数量
                        Long count = sceneTypeCountMap.get(sceneType.getId().byteValue());
                        item.setAgentCount(count != null ? count.intValue() : 0);
                        return item;
                    })
                    .collect(Collectors.toList());

            return ResponseResult.success(response);
        } catch (Exception e) {
            log.error("获取智能体场景类型列表失败", e);
            return ResponseResult.fail(500, e.getMessage());
        }
    }
}
